/*
 *@本JS功能：班级管理
 *@本js作者：杨锡君
 *@编写时间：2017年10月31日
 */
$(function() {
    var Alert1 = new Alert();
    var confirm1 = new Confirm();
    var loading1 = new Loading();
    loading1.init();
    var $chapterList = $("#chapterList");
    var $iconfont = $(".iconfont");
    var $processInfo =  $(".processInfo");
    var $processed = $(".processed");
    var $clearProcessBtn = $(".clearProcessBtn");
    var $showSection = $(".showSection");
    var $mb = $(".mb");
    var $mainContents = $(".mainContents");
    function homeworkEvaluation(opt){
        return "<div class=\"popup\" style=\"display: block;\">"
            +"<div class=\"popup_box\">"
            +"<div class=\"popup_contenthead\">作业评价<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>"
            +"<div class=\"popup_content\">"
            +"<div style=\"height: auto;min-height: 34px\"><i>作业名称&ensp;:&ensp;</i><span>"+ opt.homeworkName +"</span></div>"
            +"<div><i>作业评分&ensp;:&ensp;</i><span>"+ opt.taskFraction +"</span></div>"
            +"<div><i>作业评价&ensp;:&ensp;</i><span>"+ opt.submitContent +"</span></div>"
            +"</div>"
            +"<div class=\"clear\"></div>"
            +"<div class=\"popup_btns\">"
            +"<a class=\"popup_confirm exportBtns hover-btn\">确定</a>"
            +"</div>"
            +"<div class=\"clear\"></div>"
            +"</div>"
            +"</div>";
    }
    function homework(opt){
        return "<div class=\"popup\" >"
            +"<div class=\"popup_box\">"
            +"<div class=\"popup_contenthead\">上传作业<img class=\"popup_img\" src=\"pc/images/ico_alertDel.png\"></div>"
            +"<form id=\"upHomework\"  method=\"post\" enctype=\"multipart/form-data\">"
            +"<div class=\"popup_content\">"
            +"<label class=\"fileBtn\" for=\"file\">点击选择文件</label>"
            +"<input type=\"file\" name=\"file\" id=\"file\" style=\"display: none;\" />"
            +"<input type=\"hidden\" name=\"chapterNum\" id=\"chapterNum\" value="+ opt.chapterNum +" />"
            +"<input type=\"hidden\" name=\"courseId\" id=\"courseId\" value="+ opt.courseId +" />"
            +"<input type=\"hidden\" name=\"taskType\" id=\"taskType\" value=\"1\" />"
            +"<div class=\"fileName\"></div>"
            +"</div>"
            +"<div class=\"popup_btn\">"
            +"<button class=\"popup_confirm exportBtn exportBtnHome hover-btn\">确定</button>"
            +"<a class=\"popup_close exportCancle hover-btn\">取消</a>"
            +"</div>"
            +"<div class=\"clear\"></div>"
            +"</form>"
            +"</div>"
            +"</div>";
    }
    var num =0;
    function chapterListModel(opt,url){
        var taskAddress = opt.taskAddress;
        if(taskAddress == ""){
            taskAddress = 1;
        }
        var taskFraction =opt.taskFraction;
        if(taskFraction == undefined||taskFraction == null){
            taskFraction = "暂无";
        }
        var submitContent = opt.submitContent;
        if(submitContent == undefined||submitContent == null){
            submitContent = "暂无";
        }
        num++;
        var str = "";
        var str1 = "";
        var str2 = "";
        var str3 = "";
        str = "<li>"
            +"<a data-value=\"0\" class=\"oneChapter\"  data-chapternum="+ opt.chapterNum +" href=\"javascript:;\">"
            +"<div><span class=\"down\">"+ opt.chapterNum +"-"+ opt.chapterName +"</span></div>"
            +"</a>"
            +"<ul>";
        str1 = "<li>"
            +"<a href=\"javascript:;\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.coursewareNameHtml +"' data-value=\"1\" class=\"courseware\">学习课件"
            +"</a>"
            +"</li>";
        str1 += "<li>"
            +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.courseMaterialName +"'  class=\"courseMaterial\">备课材料</a>"
            +"</li>";
        str1 +=	"<li>"
            +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.homeworkNameHtml +"'   class=\"homework\">课后作业"
            +"</a>"
            +"</li>";
        // str1 += "<li>"
        //     +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.courseAnswerNameHtml +"'   class=\"courseAnswer\">作业答案"
        //     +"</a>"
        //     +"</li>";
        str2 = "<li>"
            +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.testDocName +"'   class=\"testDoc\">实验手册</a>"
            +"</li>"
            +"<li>"
            +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.videoName +"'  class=\"video\">学习视频</a>"
            +"</li>"
            +"<li>"
            +"<a href=\"javascript:;\" data-value=\"1\"  data-courseid="+ opt.courseId +"   data-chapternum="+ opt.chapterNum +"  data-chapterid="+ opt.chapterId +"   data-src='"+ url+ opt.expreNameHtml +"'  class=\"report choseBtn\">实验报告</a>"
            +"</li>";
        if(opt.packageFile != "" && opt.packageFile != undefined && opt.packageFile != null){
            str3 = "<li>"
                +"<a href=\"javascript:;\" data-value=\"1\" class=\"packageFile\">课程材料<img src=\"pc/images/ico_downloadFile.png\" title=\"下载\" alt=\"下载\" data-src='"+ url+ opt.packageFile +"' class=\"download fr\" /></a>"
                +"</li>"
                +"</ul>"
                +"</li>";
        }else{
            str3 = "</ul>"
                +"</li>";
        }

//			理论
        if(opt.addTestMark == 2){
            return str + str1 + str3;
        }
//			实验
        if(opt.addTestMark == 1){
            return str + str2 + str3;
        }
//			理论加实验
        if(opt.addTestMark == 3){
            return str + str1 + str2 + str3;
        }

    }
    function reportShow(opt) {
        var str = '<div style="background: #fff;" class="editSection">' +
            '<div class="fl" style="margin: 20px 0 0 0;text-align: left;padding-left: 20px;width: auto;">' +
            opt+
            '</div>' +
            '</div>';
        return str;
    }
    var myCourse = {
        init:function(){
            this.bindEvent();
        },
        bindEvent:function(){
            var self = this;
            self.getData();
            // self.getProcess();
            // $clearProcessBtn.off("click").click(function(){
            //     var courseId =  result.paramData.courseId;
            //     self.clearProcess(courseId);
            // });
            // 返回
            $(".looktg").attr("data-url",result.paramData.pageName);
        },
        clearProcess:function(courseId){
//			清楚进度
            var self = this;
            var jsonStr = JSON.stringify({
                "courseId":courseId
            });
            $.ajax({
                type:"post",
                url:"emptyProcess",
                async:true,
                data:{
                    "jsonStr":jsonStr
                },
                success:function(msg){
                    msg = JSON.parse(msg);
                    if(msg.result == "success"){
                        Alert1.content = "清除成功";
                        Alert1.success = function(){
                            self.getProcess();
                        };
                        Alert1.init();
                        Alert1.show();
                    }
                }
            });
        },
        getData:function(){
//			获取头部信息，章节列表
            var self = this;
            var jsonStr = JSON.stringify({
                "courseId":result.paramData.courseId
            });
            $.ajax({
                type:"post",
                url:"skipCourseStudyDetail",
                async:true,
                data:{
                    "jsonStr":jsonStr
                },
                success:function(msg){
                    msg = JSON.parse(msg);
                    $iconfont.html(msg.courseDetail.courseTitle);
                    $iconfont.css({"color":msg.courseDetail.courseColer,"border-color":msg.courseDetail.courseColer});
                    $iconfont.siblings("p").html(msg.courseDetail.courseName);
                    $iconfont.siblings("p").attr("title",msg.courseDetail.courseName);
                    // if(msg.process != 0){
                    //     $(".preChapter").html("上一章&emsp;"+(msg.process)+"-"+msg.chapterList[msg.process-1].chapterName);
                    // }
                    // if(msg.process < msg.chapterList.length-1){
                    //     $(".nextChapter").html("下一章&emsp;"+(msg.process+2)+"-"+msg.chapterList[msg.process+1].chapterName);
                    // }
                    var str = "";
                    var downIsOk = msg.donwload_juirs;
                    if(msg.chapterList.length!=0){
                        $.map(msg.chapterList, function(opt) {
                            str += chapterListModel(opt,msg.url);
                        });
                        $chapterList.append(str);
                        // if(result.roleId == 2){
                        //     $(".download").remove();
                        // }
                        if(downIsOk == 1){
                            $(".download").remove();
                        }
                        for(var j =0;j<$(".oneChapter").length;j++){
                            for(var i=0;i<$(".oneChapter").eq(j).next().children("li").length;i++){
                                $(".oneChapter").eq(j).next().children("li").eq(i).append("<i>"+  $(".oneChapter").eq(j).attr("data-chapternum")+"-"+ (i+1) +"."+"</i>");
                            }
                        }

                    }


                    // self.stuiedEvent(msg.studyList);
                    self.selectEvent();
                    self.btnFun(msg.url);
                    self.authority(msg.roleId);
                }
            });

        },
        authority:function(roleId){
//			权限
            if(roleId == 1){
                $(".downloadTea").remove();
                $(".clearProcessBtn").remove();
            }else if(roleId == 2){
                $(".uploadFile").remove();
            }else{
                // $(".download").remove();
                $(".clearProcessBtn").remove();
                $(".uploadFile").remove();
                $(".enterLab").off("click");
                $(".enterLab").removeClass("enterLab");
            }
        },
        stuiedEvent:function(arr){
//			学习过的章节变色
            $.map(arr, function(opt) {
                $(".oneChapter[data-chapternum*="+ opt.chapterNum +"]").attr("data-value","1");
            });

        },
        btnFun:function(url){
//			章节中按钮方法
//			查看
            var self = this;
            function videoRemove(){
                //去除video标签
                if($(".showVideo").length!=0){
                    $(".showVideo").remove();
                }
            }
//			学习课件
            $(".courseware").off("click").click(function(){
                videoRemove();
                if($(this).attr("data-src").indexOf(".pdf") != -1){
                    // self.addProcess({"chapterNum":$(this).attr("data-chapternum"),"courseId":$(this).attr("data-courseid")});
                    $showSection.attr("src","pc/js/extends/generic/web/viewer.html?file="+$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='viewer.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }
            });
            //备课材料
            $(".courseMaterial").off("click").click(function(){
                videoRemove();
                if($(this).attr("data-src").indexOf(".html") != -1){
                    $showSection.attr("src",$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }

            });
            //课后作业
            $(".homework").off("click").click(function(){
                videoRemove();
                if($(this).attr("data-src").indexOf(".html") != -1){
                    $showSection.attr("src",$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }
            });
            //作业答案
            $(".courseAnswer").off("click").click(function(){
                videoRemove();
                if($(this).attr("data-src").indexOf(".html") != -1){
                    $showSection.attr("src",$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }
            });
//			实验手册
            $(".testDoc").off("click").click(function(){
                videoRemove();
                // $(this).parent().parent().siblings("a").attr("data-value","1");
                if($(this).attr("data-src").indexOf(".html") != -1){
                    $showSection.attr("src",$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }

            });
//			学习视频
            $(".video").off("click").click(function(){
                videoRemove();
                $showSection.load(function () {
                    $showSection.contents().find("link").remove();
                });
                // self.addProcess({"chapterNum":$(this).attr("data-chapternum"),"courseId":$(this).attr("data-courseid")});
                $showSection.after("<video autoplay controls class='showVideo'  src='"+ $(this).attr("data-src") +"'></video>");
                $('.showVideo').bind('contextmenu',function() { return false; });
            });
            //下载
            $(".download").off("click").click(function(e){
                if(url == $(this).attr("data-src")){
                    Alert1.content = "当前没有文件可供下载";
                    Alert1.init();
                    Alert1.show();
                }else{
                    $(this).append("<a href=\""+ $(this).attr("data-src") +"\" download id='downFile'></a>");
                    document.getElementById("downFile").click();
                    $("#downFile").remove();
                    e.stopPropagation()
                }

            });

//			进入实验
            $(".enterLab").off("click").click(function(){
                var that = $(this);
                var flag = false;
                $.ajax({
                    type: "get",
                    url: "server/stuortea/"+result.stuorteaId,
                    async: true,
                    success: function (msg) {
                        if(msg.code == "200"){
                            if(msg.data.length != 0){
                                // self.addProcess({"chapterNum":that.attr("data-chapternum"),"courseId":that.attr("data-courseid")});
                                flag = true;

                            }else{
                                Alert1.content = "当前没有虚拟机，请先分配虚机";
                                Alert1.init();
                                Alert1.show();
                                return false;
                            }
                        }
                    }
                });

                setTimeout(function (args) {
                    if(flag == true){
                        self.enterLab(that);
                    }

                },200);


            });
            //实验报告
            $(".report").off("click").click(function () {
                videoRemove();
                if($(this).attr("data-src").indexOf(".html") != -1){
                    $showSection.attr("src",$(this).attr("data-src"));
                    $showSection.load(function () {
                        $showSection.contents().find("link").remove();
                        $showSection.contents().find("title").before("<link href='../../pc/css/cores/marxico.css' rel='stylesheet'>");
                    });
                }else{
                    $showSection.attr("src","pc/page/noResourceShow.html");
                }

            });
//			上传作业
            $(".uploadFile").off("click").click(function(e){
                var str = homework({"chapterNum":Number($(this).attr("data-chapternum")),"courseId":($(this).attr("data-courseid"))});
                $mainContents.append(str);
                $mb.show();
                self.fileUpEvent($(this));
                self.cancleFile();
                e.stopPropagation();
            });
//			查看作业评价
            $(".evaluate").off("click").click(function(){
                if($(this).attr("data-taskAddress") == 1){
                    Alert1.content = "当前章节未提交作业，请先提交作业";
                    Alert1.init();
                    Alert1.show();
                    return false;
                }
                var homeworkName = $(this).attr("data-homeworkname");
                var submitContent = $(this).attr("data-submitcontent");
                var taskFraction = $(this).attr("data-taskfraction");
                if(submitContent == "暂无"){
                    submitContent = "暂无评价"
                }
                if(taskFraction == "暂无"){
                    taskFraction = "暂无评价"
                }
                $mb.show();
                var str = homeworkEvaluation({"homeworkName":homeworkName,"taskFraction":taskFraction,"submitContent":submitContent});
                $mainContents.append(str);
                self.evaluateEvent();
            });
        },
        evaluateEvent:function(){
//			 评价按钮事件
            $(".exportBtns").click(function(){
                $mb.hide();
                $(".popup").remove();
            });
            $(".popup_img").click(function(){
                $mb.hide();
                $(".popup").remove();
            });
        },
        cancleFile:function(){
//			取消上传作业
            $(".exportCancle").click(function(){
                $mb.hide();
                $(".popup").remove();
            });
            $(".popup_img").click(function(){
                $mb.hide();
                $(".popup").remove();
            });
        },
        fileUpEvent:function(opt){
//			文件上传事件
            $("#file").change(function() {
                var type = $(this).val().substring($(this).val().lastIndexOf(".")).toLowerCase(); // 取文件格式后缀名
                if(type != ".doc" && type != ".docx") {
                    $("#file").val("");
                    Alert1.content = "请上传word文件，谢谢合作！";
                    Alert1.init();
                    Alert1.show();
                    return false;
                } else {
                    var filename = $(this).val().substring($(this).val().lastIndexOf("\\")+1);
                    $(".fileName").html("已选:"+filename);
                    return true;
                }
            });
            $(".exportBtnHome").off("click").click(function () {
                if ($(".fileName").html() == "") {
                    Alert1.content = "请先上传文件，谢谢合作！";
                    Alert1.init();
                    Alert1.show();
                }else{
                    $("#upHomework").off("submit").submit(function (event) {

                        loading1.show();
                        var formData = new FormData(this);
                        setTimeout(function (args) {
                            $.ajax({
                                url: 'stuUploadHomework',
                                type: 'post',
                                data: formData,
                                async: false,
                                cache: false,
                                contentType: false,
                                processData: false,
                                success: function (msg) {
                                    loading1.hide();
                                    msg = JSON.parse(msg);
                                    if(msg.result == "success"){
                                        Alert1.content = "上传作业成功";
                                        Alert1.success = function(){
                                            $mb.hide();
                                            $(".popup").remove();
                                            opt.parent().html(opt.parent().html().replace("未提交","未审核"));
                                        };
                                        Alert1.init();
                                        Alert1.show();
                                        return false;
                                    }else{
                                        Alert1.content = msg.failMsg;
                                        Alert1.init();
                                        Alert1.show();
                                        return false;
                                    }
                                }
                            });
                        },1000);
                        return false;
                    });
                }
            });

        },
        enterLab:function(opt){
//			进入实验
            var self = this;
            var flag = false;
            var jsonStr = JSON.stringify({"chapterNum":Number(opt.attr("data-chapternum")),"courseId":Number(opt.attr("data-courseid"))});
            $.ajax({
                type:"post",
                url:"saveEnvironmentParam",
                async:true,
                data:{
                    "jsonStr":jsonStr
                },
                success:function(msg){
                    msg = JSON.parse(msg);
                    if(msg.result == "success"){
                        flag = true;
                    }
                }
            });
            loading1.show();
            setTimeout(function (args) {
                loading1.hide();
                if(flag == true){
                    window.open("skipEnvironment",'_blank');
                }else{
                    Alert1.content = "进入实验环境失败";
                    Alert1.init();
                    Alert1.show();
                }

            },200);
            // var json = JSON.stringify({
            // "pageName":"labEnvirments",
            // "paramData":{"chapterNum":Number(opt.attr("data-chapternum")),"courseId":Number(opt.attr("data-courseid"))}
            // });
            // // "paramData":{"chapterNum":Number(opt.attr("data-chapternum")),"courseId":Number(opt.attr("data-courseid")),"video":opt.attr("data-video")}
            // // top.location.href = "skipPage?jsonStr="+json;
            // window.open("skipPage?jsonStr="+json,'_blank');
        },
        addProcess:function(opt){
//			添加进度
//             var self = this;
//             var jsonStr = JSON.stringify(opt);
            // $.ajax({
            //     type:"post",
            //     url:"addProcess",
            //     async:true,
            //     data:{
            //         "jsonStr":jsonStr
            //     },
            //     success:function(msg){
            //         msg = JSON.parse(msg);
            //         if(msg.result == "success"){
            //             self.getProcess();
            //         }
            //     }
            // });
        },
        getProcess:function(){
            //获取学习进度
            var json = JSON.stringify({
                "courseId": result.paramData.courseId,
                "stuorteaId": result.stuorteaId
            });
            // $.ajax({
            //     type:"post",
            //     url:"getMyProcess",
            //     async:true,
            //     data:{
            //         "jsonStr":json
            //     },
            //     success:function(msg){
            //         msg = JSON.parse(msg);
            //         $processInfo.html("已进行"+ msg.process +"/"+ msg.totalLength +"课时");
            //         $processed.animate({
            //             width:(msg.process)/(msg.totalLength)*100+"%"
            //         },"slow")
            //     }
            //
            // });
        },
        selectEvent:function(){
            /*导航下拉展开事件*/
            $(".left span").click(function() {
                if($(this).hasClass("up")) {
                    $(this).removeClass("up");
                    $(this).addClass("down");
                    $(this).parent().parent().parent().find("ul").slideToggle(300);
                } else {
                    $(".left ul li ul").slideUp(300);
                    $(".left ul li span").removeClass("up");
                    $(".left ul li span").addClass("down");
                    $(this).removeClass("down");
                    $(this).addClass("up");
                    $(this).parent().parent().parent().find("ul").slideToggle(300);
                }
            });
        }
    };
    myCourse.init();
});